﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.IO;

namespace Bilyteam_Website.Admin
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        DataTable tbGalleries = new DataTable();
        DataTable tbImages = new DataTable();
        private string imageLocation = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }

            if (Page.IsPostBack)
            {
                if (fupImage.HasFile)
                {
                    imageLocation = fupImage.FileName;
                }
            }
        }

        private void BindData()
        {
            BindGalleries();
            BindImages();
        }

        private void BindImages()
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            cmd.Connection = conn;
            cmd.CommandText = "Select * From Images Where Status = 'True' Order By ImageID Asc";
            cmd.CommandType = CommandType.Text;
            da.SelectCommand = cmd;
            da.Fill(ds, "Images");
            tbImages = ds.Tables["Images"];

            dtlImages.DataSource = tbImages;
            dtlImages.DataBind();
        }

        private void BindGalleries()
        {
 	        conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            cmd.Connection = conn;
            cmd.CommandText = "Select * From Galleries Where Status = 'True' Order By GalleryID Asc";
            cmd.CommandType = CommandType.Text;
            da.SelectCommand = cmd;
            da.Fill(ds, "Galleries");
            tbGalleries = ds.Tables["Galleries"];

            dtlGalleries.DataSource = tbGalleries;
            dtlGalleries.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string galleryName = txtGalleryName.Text;
            string galleryDes = txtGalleryDes.Text;
            bool status = true;

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Insert Into Galleries Values (@GalleryName, @GalleryDescription, @Status);";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@GalleryName", SqlDbType.NVarChar);
            cmd.Parameters.Add("@GalleryDescription", SqlDbType.NVarChar);
            cmd.Parameters.Add("@Status", SqlDbType.Bit);
            cmd.Parameters[0].Value = galleryName;
            cmd.Parameters[1].Value = galleryDes;
            cmd.Parameters[2].Value = status;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                BindGalleries();
                lblMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                txtGalleryName.Text = "";
                txtGalleryDes.Text = "";
                lblMessage.Text = "Add gallery successfully !!";
            }
            else
            {
                lblMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblMessage.Text = "Add gallery falied !!";
            }
        }

        protected override void OnInit(EventArgs e)
        {
            Page.EnableViewState = true;
            base.OnInit(e);
        }

        protected void btnAddImage_Click(object sender, EventArgs e)
        {
            string strGuid = createString(10);
            string imageName = txtImageName.Text;
            string location = "Images/NoImage.gif";
            String path = Server.MapPath("~/Images/Galleries");
            string fileSave = path + "/" + strGuid + fupImage.FileName;

            if (fupImage.HasFile)
            {
                location = "Images/Galleries/" + strGuid + fupImage.FileName;
            }

            bool status = true;

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Insert Into Images Values (@ImageName, @Location, @Status);";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@ImageName", SqlDbType.NVarChar);
            cmd.Parameters.Add("@Location", SqlDbType.NVarChar);
            cmd.Parameters.Add("@Status", SqlDbType.Bit);
            cmd.Parameters[0].Value = imageName;
            cmd.Parameters[1].Value = location;
            cmd.Parameters[2].Value = status;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                try
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    if (fupImage.HasFile)
                    {
                        fupImage.SaveAs(fileSave);
                    }
                }
                catch
                {
                }
                BindImages();
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                lblImageMessage.Text = "Add image successfully !!";
            }
            else
            {
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblImageMessage.Text = "Add image failed !!";
            }
            txtImageName.Focus();
        }

        private string createString(int length)
        {
            string _allowedChars = "abcdefghijkmnopqrstuvwxyz0123456789";
            Random randNum = new Random();
            char[] chars = new char[length];
            int allowedCharCount = _allowedChars.Length;

            for (int i = 0; i < length; i++)
            {
                chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
            }
            return new string(chars);
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            string galleryName = txtGalleryName.Text;
            string galleryDes = txtGalleryDes.Text;
            int galleryID = 1;
            if (hdGalleryIDValue.Value != "")
            {
                galleryID = Convert.ToInt32(hdGalleryIDValue.Value);
            }
            else
            {
                lblMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblMessage.Text = "Please select gallery to update !!";
                return;
            }

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Update Galleries Set GalleryName = @GalleryName, GalleryDescription = @GalleryDescription Where GalleryID = @GalleryID;";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@GalleryName", SqlDbType.NVarChar);
            cmd.Parameters.Add("@GalleryDescription", SqlDbType.NVarChar);
            cmd.Parameters.Add("@GalleryID", SqlDbType.Int);
            cmd.Parameters[0].Value = galleryName;
            cmd.Parameters[1].Value = galleryDes;
            cmd.Parameters[2].Value = galleryID;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                BindGalleries();
                txtGalleryName.Text = galleryName;
                txtGalleryDes.Text = galleryDes;
                lblMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                lblMessage.Text = "Update gallery successfully !!";
            }
            else
            {
                lblMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblMessage.Text = "Update gallery failed !!";
            }
        }

        protected void dtlGalleries_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Attributes.Add("onmouseover", "this.oldClass = this.className; this.className = 'EntryLineHover'");
                e.Item.Attributes.Add("onmouseout", "this.className = this.oldClass;");
                e.Item.Attributes.Add("onclick", this.Page.ClientScript.GetPostBackEventReference(e.Item.Controls[1], string.Empty));
            }
        }

        protected void dtlGalleries_ItemCommand(object source, DataListCommandEventArgs e)
        {
            hdGalleryIDValue.Value = ((HiddenField)e.Item.FindControl("hdGalleryID")).Value;
            txtGalleryName.Text = ((Label)e.Item.FindControl("lblGalleryName")).Text;
            txtGalleryDes.Text = ((Label)e.Item.FindControl("lblGalleryDes")).Text;
            lblMessage.Text = "";
            txtGalleryName.Focus();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int galleryID = 1;
            bool status = false;
            if (hdGalleryIDValue.Value != "")
            {
                galleryID = Convert.ToInt32(hdGalleryIDValue.Value);
            }
            else
            {
                lblMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblMessage.Text = "Please select gallery to delete !!";
                return;
            }

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Update Galleries Set Status = @Status Where GalleryID = @GalleryID;";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Status", SqlDbType.Bit);
            cmd.Parameters.Add("@GalleryID", SqlDbType.Int);
            cmd.Parameters[0].Value = status;
            cmd.Parameters[1].Value = galleryID;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                BindGalleries();
                txtGalleryName.Text = "";
                txtGalleryDes.Text = "";
                lblMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                lblMessage.Text = "Delete gallery successfully !!";
            }
            else
            {
                lblMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblMessage.Text = "Delete gallery failed !!";
            }
        }

        protected void btnUpdateImage_Click(object sender, EventArgs e)
        {
            string strGuid = createString(10);
            string imageName = txtImageName.Text;
            string location = "Images/NoImage.gif";
            String path = Server.MapPath("~/Images/Galleries");
            String pathDelete = "";
            string fileSave = path + "/" + strGuid + fupImage.FileName;

            if (fupImage.HasFile)
            {
                location = "Images/Galleries/" + strGuid + fupImage.FileName;
            }

            int imageID = 1;
            if (hdIDImageValue.Value != "")
            {
                imageID = Convert.ToInt32(hdIDImageValue.Value);
                pathDelete = Server.MapPath("~/" + hdLocationValue.Value);
            }
            else
            {
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblImageMessage.Text = "Please select image to update !!";
                return;
            }

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Update Images Set ImageName = @ImageName, Location = @Location Where ImageID = @ImageID;";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@ImageName", SqlDbType.NVarChar);
            cmd.Parameters.Add("@Location", SqlDbType.NVarChar);
            cmd.Parameters.Add("@ImageID", SqlDbType.Int);
            cmd.Parameters[0].Value = imageName;
            cmd.Parameters[1].Value = location;
            cmd.Parameters[2].Value = imageID;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                try
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    if (File.Exists(pathDelete))
                    {
                        File.Delete(pathDelete);
                    }

                    if (fupImage.HasFile)
                    {
                        fupImage.SaveAs(fileSave);
                    }
                }
                catch
                {
                }
                BindImages();
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                lblImageMessage.Text = "Update image successfully !!";
            }
            else
            {
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblImageMessage.Text = "Update image failed !!";
            }
            txtImageName.Focus();
        }

        protected void dtlImages_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Attributes.Add("onmouseover", "this.oldClass = this.className; this.className = 'EntryLineHover'");
                e.Item.Attributes.Add("onmouseout", "this.className = this.oldClass;");
                e.Item.Attributes.Add("onclick", this.Page.ClientScript.GetPostBackEventReference(e.Item.Controls[1], string.Empty));
            }
        }

        protected void dtlImages_ItemCommand(object source, DataListCommandEventArgs e)
        {
            hdIDImageValue.Value = ((HiddenField)e.Item.FindControl("hdImageID")).Value;
            hdLocationValue.Value = ((HiddenField)e.Item.FindControl("hdLocation")).Value;
            txtImageName.Text = ((Label)e.Item.FindControl("lblImageName")).Text;
            lblImageMessage.Text = "";
            txtImageName.Focus();
        }

        protected void btnDeleteImage_Click(object sender, EventArgs e)
        {
            String pathDelete = "";

            int imageID = 1;
            if (hdIDImageValue.Value != "")
            {
                imageID = Convert.ToInt32(hdIDImageValue.Value);
                pathDelete = Server.MapPath("~/" + hdLocationValue.Value);
            }
            else
            {
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblImageMessage.Text = "Please select image to delete !!";
                return;
            }
            
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PROJECT"].ConnectionString;
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = "Delete From ImageToGallery Where IDImage = @ImageID; Delete From Images Where ImageID = @ImageID;";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@ImageID", SqlDbType.Int);
            cmd.Parameters[0].Value = imageID;
            int process = cmd.ExecuteNonQuery();
            conn.Close();

            if (process > 0)
            {
                try
                {
                    if (File.Exists(pathDelete))
                    {
                        File.Delete(pathDelete);
                    }
                }
                catch
                {
                }
                BindImages();
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("#009900");
                lblImageMessage.Text = "Delete image successfully !!";
            }
            else
            {
                lblImageMessage.ForeColor = ColorTranslator.FromHtml("Red");
                lblImageMessage.Text = "Delete image failed !!";
            }
            txtImageName.Focus();
        }
    }
}